import axios from "axios";
import qs from "qs";
import { Toast } from 'vant';

function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
  return unescape(r[2]);
  }
  return null;
}

let config = {
    baseURL: 'http://natcross.nikolee.com:2828',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}
let gloabLoading = null;
const axiosHttp = axios.create(config);

let userInfo={
  userId:getQueryString("userId"),
  Authorization:getQueryString("Authorization"),
}

axiosHttp.interceptors.request.use(function (config) {
    gloabLoading = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration:0,
      });    
    // 在发送请求之前做些什么
    if(config.params&&config.params.userId){
    }else{
        config.params&&!config.params.userId?(config.params.userId=userInfo.userId):(config.params={userId:userInfo.userId});
    }
    config.data&&!config.data.userId?(config.data.userId=userInfo.userId):(config.data={userId:userInfo.userId});
    config.headers['Authorization'] = 'Bearer '+userInfo.Authorization;
    
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axiosHttp.interceptors.response.use(function (response) {
    gloabLoading&&gloabLoading.clear();
    // 对响应数据做点什么
    // console.log(response)
    if(response.data.code!=0||!response.data.success){
        Toast(response.data.msg);
        return Promise.reject(response.data.msg);
    }
    return response.data;
  }, function (error) {
    console.log(error);
    gloabLoading&&gloabLoading.clear();
    // 对响应错误做点什么
    if(error.message.indexOf("timeout")>-1){
        Toast("请求超时");
    }else{
        Toast(error);
    }
   
    return Promise.reject(error);
  });


export default axiosHttp